<?php
class Pagging{
	static $totalPage = 1, $recPerPage = 10, $page = 1, $totalResult = 0;

	static function pager_query(&$sql = '',$itemperpage=10,$page_name = 'page_no'){
		if(self::getTotalPage($sql, $itemperpage)){
			$page = FunctionLib::getParamInt($page_name, 1);
			if($page <= 0){
				$page = 1;
			}
			if($page > self::$totalPage){
				$page = self::$totalPage;
			}
			self::$page = $page;
			self::$recPerPage = $itemperpage;

			$stripos_limit = stripos($sql,'limit');
			if($stripos_limit !== false){
				$sql = substr($sql, 0, $stripos_limit);
			}
			$sql .= ' LIMIT '.($page - 1)*$itemperpage.', '.$itemperpage;
			return DB::query($sql);
		}
		return false;
	}

	static function getTotalPage($sql = '', $itemperpage = 10){
		if($itemperpage > 0){
			$count = "SELECT count(*) as total ".substr($sql, stripos($sql,'from'), strlen($sql));
			$count = DB::query($count);
			if($count = @mysql_fetch_assoc($count)){
				self::$totalResult = $count['total'];
				return self::$totalPage = ceil(self::$totalResult/$itemperpage);
			}
		}
		return false;
	}

	static function getPager($numPageShow = 10, $showTotalPage = false, $page_name = 'page_no'){
		if(self::$totalPage == 1) return '';
		$next = '';
		$last = '';
		$prev = '';
		$first= '';
		$left_dot  = '';
		$right_dot = '';
		$from_page = self::$page - $numPageShow;
		$to_page = self::$page + $numPageShow;

		//get prev & first link
		if(self::$page > 1){
			$prev = self::parseLink(self::$page-1, 'page-item prev', "Trước", $page_name);
			$first= self::parseLink(1, 'page-item first', "Đầu", $page_name);
		}
		//get next & last link
		if(self::$page < self::$totalPage){
			$next = self::parseLink(self::$page+1, 'page-item next', "Sau", $page_name);
			$last = self::parseLink(self::$totalPage, 'page-item last', "Cuối", $page_name);
		}
		//get dots & from_page & to_page
		if($from_page > 0)	{
			$left_dot = ($from_page > 1) ? '<span class="dot">...</span>' : '';
		}else{
			$from_page = 1;
		}

		if($to_page < self::$totalPage)	{
			$right_dot = '<span class="dot">...</span>';
		}else{
			$to_page = self::$totalPage;
		}
		$pagerHtml = '';
		for($i=$from_page;$i<=$to_page;$i++){
			$pagerHtml .= self::parseLink($i, ((self::$page == $i) ? 'page-item active' : 'page-item'), $i, $page_name);
		}
		return '<div class="pager">'.$first.$prev.$left_dot.$pagerHtml.$right_dot.$next.$last.'</div>';
	}

	static function parseLink($page = 1, $class="", $title="", $page_name = 'page_no'){
		$param = $_GET;
		$param['page_no'] = $page;
		unset($param['page']);
		if(isset($param['form_block_id'])){
			unset($param['form_block_id']);
		}
		$pageName = Url::get('page','');
		return '<a href="'.Url::build($pageName,$param).'" class="'.$class.'" title="xem trang '.$title.'"><span>'.$title.'</span></a>';
	}
}
?>